package com.iraeta.service.sys.impl;

import com.iraeta.dao.sys.SysOrgDao;
import com.iraeta.entity.CustomOrg;
import com.iraeta.entity.SysOrg;
import com.iraeta.entity.TreeNode;
import com.iraeta.service.sys.ISysOrgService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysOrgServiceImpl implements ISysOrgService {
    @Resource
    SysOrgDao sysOrgDao;

    @Transactional
    @Override
    public void addOrg(SysOrg sysOrg) {
        sysOrgDao.insert(sysOrg);
        SysOrg pSysOrg = sysOrgDao.selectByPrimaryKey(sysOrg.getPid());
        if(pSysOrg != null){
            sysOrg.setMember(pSysOrg.getMember() + "," + sysOrg.getId());
        }else{
            sysOrg.setMember(CustomOrg.root + "," + sysOrg.getId());
        }
        sysOrgDao.updateByPrimaryKey(sysOrg);
    }

    @Override
    public void updateOrg(SysOrg sysOrg) {
        sysOrgDao.updateByPrimaryKey(sysOrg);
    }

    @Override
    public void deleteOrg(Integer orgId) {
        sysOrgDao.deleteByPrimaryKey(orgId);
    }

    @Override
    public SysOrg getOrg(Integer orgId) {
        return sysOrgDao.selectByPrimaryKey(orgId);
    }

    /*获取组织下的所有机构的 树形结构*/
    @Override
    public List<TreeNode> listChildrenOrg(Integer orgId){
        String orgIdStr = String.valueOf(orgId);
        List<SysOrg> sysOrgList = sysOrgDao.selectAllChildrenOrg(orgId);
        SysOrg rootSysOrg = sysOrgList.stream().filter(x->x.getId().toString().equals(orgIdStr)).findFirst().get();
        TreeNode rootTreeNode = new TreeNode(rootSysOrg.getId().toString(), rootSysOrg.getName());
        listChildrenOrgLoop(rootTreeNode, sysOrgList);
        ArrayList<TreeNode> res = new ArrayList<>();
        res.add(rootTreeNode);
        return res;
    }
    private void listChildrenOrgLoop(TreeNode treeNode, List<SysOrg> sysOrgList){
        String orgIdStr = String.valueOf(treeNode.id);
        List<SysOrg> childOrgList = sysOrgList.stream().filter(x-> x.getPid().toString().equals(orgIdStr)).collect(Collectors.toList());
        for(SysOrg childOrg : childOrgList){
            TreeNode childTreeNode = new TreeNode(childOrg.getId().toString(), childOrg.getName());
            treeNode.addNode(childTreeNode);
            listChildrenOrgLoop(childTreeNode, sysOrgList);
        }
    }
}
